#pragma once

#include <string>
#include <QString>
#include "modbus.h"

#include "qmodbusdevice_global.h"

// modbus主站：rtu模式下的master，tcp模式下的client
enum mb_connect_type { serial = 0, tcp };

struct ModbusSettings
{
	// 串口参数
	QString serialName = "COM1";
	int baud = 115200;
	char parity = 'N';
	int dataBit = 8;
	int stopBit = 2;
	// tcp参数
	QString addressIP = "127.0.0.1";
	int tcpPort = 502;

	int slaveId = 1;
};

enum func_code {
	read_coils = 0, read_discrete_inputs, read_holding_registers, read_input_registers,
	write_single_coil, write_single_register, write_multi_coils, write_multi_registers
};

class QMODBUSDEVICE_EXPORT ModbusPoll
{
public:
	ModbusPoll();

	bool connect();
	bool isConnected() { return isConnected_; }
	// 连接
	bool connectDeviceSerial(const char* deviceName, int baud, char parity = 'N', int dataBit = 8, int stopBit = 2);
	bool connectDeviceTcp(const char* ip, int port);

	void setConnectType(mb_connect_type type) { connectType_ = type; }
	mb_connect_type getConnectType() { return connectType_; }

	void setSlave(int slaveId) { modbus_set_slave(modbusDevice_, slaveId); }
	int getSlaveId() { return modbus_get_slave(modbusDevice_); }

	void disconnectDevice();

	void setSettings(ModbusSettings* settings) { modbusSettings_ = *settings; }
	ModbusSettings* getSettings() { return &modbusSettings_; }

	int readCoils(uint8_t* data, int address, int num);
	int writeCoil(uint8_t data, int address);
	int writeCoils(uint8_t* data, int address, int num);

	int readRegister(uint16_t* data, int address);
	int readRegisters(uint16_t* data, int address, int num);

	int writeRegister(uint16_t data, int address);
	int writeRegisters(uint16_t* reg, int startAddress, int num);

	// 加载和保存
	bool read(const char* modbus);
	bool write(const char* modbus);

private:
	modbus_t* modbusDevice_ = nullptr;
	bool isConnected_ = false;

	mb_connect_type connectType_;
	ModbusSettings modbusSettings_;
};

